/**
 * 版本信息管理
 * wangmei
 */

import React, {Component} from 'react';
import {Table, Row, Col, Button, Upload, message, Modal, Select, Checkbox, Form} from 'antd';
import * as Request from '../../Server/Upgrade';
import * as config from '../../axios/config';
import BreadcrumbCustom from '../BreadcrumbCustom';
import * as Const from '../../common/const';
import * as Utils from '../../common/utils';
import TablePage from '../TablePage';
import qs from 'qs';

import {AuthButton, AuthA} from '../auth/OperationAuth';

require('../systemManager/customer.css');

const defaultPage = {page: Const.DEFAULT_PAGE, size: Const.DEFAULT_PAGE_SIZE};
const confirm = Modal.confirm;
const Option = Select.Option;
let checkState = false;
let permissions = undefined;

class VersioninfoManger extends Component {
    constructor(props) {
        super(props);
        checkState = false;
        this.state = {
            visible: false,
            row: {}, //单条记录信息
            loading: false, //表格加载样式
            data: [], //表格数据
            pagination: {}
        };
        permissions = JSON.parse(localStorage.getItem('user')).permission;
    }

    componentWillMount() {
        let versionPage = JSON.parse(localStorage.getItem('versionPage'));
        versionPage = versionPage ? versionPage : defaultPage;
        this.getTableData({...versionPage, inuse: checkState});
        localStorage.removeItem('versionPage');
    }

    //查询表格数据方法
    getTableData = (param) => {
        const {pagination} = this.state
        this.setState({loading: true});
        const _param = qs.stringify(param);
        Request.getVersionInfo(_param).then(res => {
            if (res && res.code == Const.REQUEST_SUCCESS) {
                const data = res.data;
                this.setState({
                    data: data.content,
                    loading: false,
                    pagination: Object.assign(pagination, {
                        total: data.totalSize,
                        current: data.page + 1,
                        pageSize: data.size
                    }),
                });
            } else {
                res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg);
            }
        });
    }

    //导入成功方法
    importSuccessFunc = (file) => {
        if (file && file.code == Const.REQUEST_SUCCESS) {
            message.success("文件导入成功", Const.AUTO_DISAPPEAR_TIME);
            this.getTableData({page: 0, size: this.currentPageSize(), inuse: checkState});
        } else {
            message.error(file.msg, Const.ERROR_DISAPPEAR_TIME);
        }
    }

    //checkBox改变方法
    checkChange = (e) => {
        checkState = e.target.checked;
        this.getTableData({page: Const.DEFAULT_PAGE, size: this.currentPageSize(), inuse: checkState});
    }

    /* 翻页 */
    handleTableChange = (pagination) => {
        const pager = {...this.state.pagination};
        pager.current = pagination.current;
        pager.pageSize = pagination.pageSize;
        this.setState({
            pagination: pager
        });
        this.getTableData({
            page: pagination.current - 1,//后台分页默认从第0页开始
            size: pagination.pageSize,
            inuse: checkState
        });
    }

    //删除方法
    deleteFunc = (row) => {
        const param = {
            id: row.id
        };
        const _param = qs.stringify(param);
        confirm({
            title: '确定要删除该条信息？',
            maskClosable: true,
            okText: "确定",
            cancelText: "取消",
            onOk: () => this.onOkFunc(_param),
            onCancel() {
            },
        });
    }

    //删除确认方法
    onOkFunc = (_param) => {
        const {pagination} = this.state;
        const current = pagination.current;
        Request.versionInfoDelete(_param).then(res => {
            if (res && res.code == Const.REQUEST_SUCCESS) {
                message.success("删除成功", Const.AUTO_DISAPPEAR_TIME);
                this.getTableData(this.getPageParams(true));
            } else {
                res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg, Const.ERROR_DISAPPEAR_TIME);
            }
        });
    }

    getPageParams = (isDelete) => {
        const {pagination} = this.state;
        const params = {
            page: pagination.current - 1,//后台分页默认从第0页开始
            size: pagination.pageSize || Const.DEFAULT_PAGE_SIZE,
            inuse: checkState
        };
        if (isDelete && pagination.current == Math.ceil(pagination.total / pagination.pageSize)
            && pagination.total % pagination.pageSize == 1) {
            params.page > 0 && params.page--;
        }
        return params;
    }

    //改变数据状态
    changeState = (tag, id) => {
        const param = {
            tag: tag,
            id: id
        };
        const _param = qs.stringify(param);
        const {pagination} = this.state;
        const current = pagination.current;
        Request.versionInfoUpdateTag(_param).then(res => {
            if (res && res.code == Const.REQUEST_SUCCESS) {
                message.success("修改成功", Const.AUTO_DISAPPEAR_TIME);
                this.getTableData({page: current ? current - 1 : 0, size: this.currentPageSize(), inuse: checkState});
            } else {
                res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg, Const.ERROR_DISAPPEAR_TIME);
            }
        });
    }

    //选择框页面跳转
    onChange = (value, id) => {
        const {history} = this.props;
        const item = Const.OPTIONDATA.filter(v => v.value == value)[0];
        if (item.url != '') {
            history.push(item.url + id);
        }
    }

    //全部备份方法
    onClickFunc = () => {
        confirm({
            title: '确定要全部备份？',
            maskClosable: true,
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
            },
            onCancel() {
            },
        });
    }

    currentPageSize = () => this.state.pagination.pageSize || Const.DEFAULT_PAGE_SIZE;

    //添加信息点击
    addClick = (id) => {
        const {pagination} = this.state
        let current = pagination.current
        const obj = {
            page: current ? current - 1 : 0, size: this.currentPageSize()
        }
        localStorage.setItem('versionPage', JSON.stringify(obj));
        this.props.history.push('/app/upgrade/version/add/' + id);
    }

    outPutClick = () =>{
        this.props.history.push('/app/upgrade/version/outPut');
    }

    render() {
        const {visible, row, loading, data, pagination} = this.state;
        const {getFieldDecorator} = this.props.form;
        const user = JSON.parse(localStorage.getItem('user'));
        let rowState = permissions.includes('version:save') || permissions.includes('version:delete');
        //批量导入配置文件
        const uploaderProps = {
            action: config.VERSIONINFO_GET_IMPORT,
            headers: {
                authorization: 'authorization-text',
            },
            fileList: [],
            onSuccess: this.importSuccessFunc //文件请求完成返回方法
        };
        let options = Const.OPTIONDATA.map((item) =>
            <Option value={item.value} key={item.value}>
                {item.title}
            </Option>
        );

        const columns = [
            {
                title: "主键",
                dataIndex: "id",
                align: 'center',
                width: '6%'
            }, {
                title: "默认下载地址",
                dataIndex: "svrRoot",
                align: 'center',
                width: '18%',
            }, {
                title: "客户端版本",
                dataIndex: "clientversion",
                align: 'center',
                width: '8%',
            }, {
                title: "升级后版本",
                dataIndex: "patchversion",
                align: 'center',
                width: '8%',
            }, {
                title: "下载到本地路径",
                dataIndex: "downdir",
                align: 'center',
                width: '15%',
            }, {
                title: "版本类型",
                dataIndex: "vertype",
                align: 'center',
                width: '9%',
                render: (text, record) => {
                    let obj = Const.VERTYPE.filter(v => v.value == text)[0];
                    return obj ? obj.title : "";
                }
            }, {
                title: "备注",
                dataIndex: "remark",
                align: 'center',
                width: '8%',
            }, {
                title: "状态",
                dataIndex: "tag",
                align: 'center',
                width: '5%',
                render: (text, record) => {
                    if (text == 0) {
                        return <text style={{color: 'red'}}>禁用</text>
                    } else {
                        return <text style={{color: '#32CD32'}}>在用</text>
                    }
                }
            }, {
                title: "详情信息",
                dataIndex: "detailInfo",
                key: 'detailInfo',
                align: 'center',
                width: '12%',
                colSpan: rowState ? 1 : 2,
                render: (text, record) => {
                    if (!rowState) {
                        const obj = {
                                children: <Select style={{width: rowState?'100%':'50%'}}
                                defaultValue=''
                                onChange={(value) => this.onChange(value, record.id)}>
                                    {options}
                                </Select>,
                                props: {},
                            }
                        ;
                        obj.props.colSpan = 2;
                        return obj;
                    }
                    return <Select style={{width: '100%'}}
                            defaultValue=''
                            onChange={(value) => this.onChange(value, record.id)} >
                        {options}
                    </Select>
                }
            }, {
                title: "操作",
                align: 'center',
                width: '0%',
                colSpan: rowState ? 1 : 0,
                render: (text, record) => {
                    if (rowState) {
                        return <span>
                            {record.tag == 0 ? <AuthA className='operation-primary' permission={'version:save'}
                                onClick={() => this.changeState(1, record.id)}>启动</AuthA> : <AuthA
                                className='operation-primary' permission={'version:save'}
                                onClick={() => this.changeState(0, record.id)}>禁用</AuthA>}
                            <AuthA className='operation-primary' permission={'version:save'}
                                   onClick={() => this.addClick(record.id)}>
                                编辑
                            </AuthA>
                            <AuthA className='operation-danger' onClick={() => this.deleteFunc(record)}
                                   permission={'version:delete'}>删除</AuthA>
                        </span>
                    }
                    const obj = {
                        children: <span></span>,
                        props: {},
                    };
                    obj.props.colSpan = 0;
                    return obj;
                }
            }
        ];

        const checkLayout = {
            xs: 24,
            sm: {span: 24},
            md: {span: 5, offset: 6},
            lg: {span: 3, offset: 14}
        }

        return (
            <div>
                <BreadcrumbCustom first={"版本信息表"}/>
                <Row>
                    <Row className="ant-form-item">
                        <Col {...Utils.getButtonCol('version:save')} className="button-margin">
                            <AuthButton size='large' permission={'version:save'} onClick={() => this.addClick(' ')}>
                                添加信息
                            </AuthButton>
                        </Col>
                        <Col {...Utils.getButtonCol('version:save')} className="button-margin">
                            <Upload {...uploaderProps}>
                                <AuthButton size='large' permission={'version:save'}>
                                    导入版本
                                </AuthButton>
                            </Upload>
                        </Col>
                        <Col {...Utils.getButtonCol('version:get')} className="button-margin">
                            <AuthButton size='large' permission={'version:get'} onClick={this.outPutClick}>
                                导出版本
                            </AuthButton>
                        </Col>
                        {/* <Col span={2} className="button-margin">
                            <Button size='large' onClick={() => this.onClickFunc()}>全部备份</Button>
                        </Col> */}
                        <Col {...Utils.getCheckCol('version:save')} >
                            <Checkbox onChange={this.checkChange} style={{marginTop: 15}}>只显示在用版本</Checkbox>
                        </Col>
                    </Row>
                    <TablePage
                        dataSource={data}
                        loading={loading}
                        columns={columns}
                        pagination={pagination}
                        onChange={this.handleTableChange}
                    />
                </Row>
            </div>
        )
    }
}

export default Form.create()(VersioninfoManger)